﻿Imports Newtonsoft.Json
Imports System.Net
Imports System.Text

Public Class Tel400

    Private web As New HttpClient
    Public TelNo As String = String.Empty
    Public TelPass As String = String.Empty
    Public TelProtectedPass As String = String.Empty
    Public TelId As Integer = -1
    Public Domain As String = "www.c4006.com"
    'Private isLogin As Boolean = False                  '是否登录
    'Private isprotect As Boolean = True                 '是否保存模式

    Public Property Cookies As CookieContainer
        Get
            Return web.Cookies
        End Get
        Set(ByVal value As CookieContainer)
            web.Cookies = value
        End Set
    End Property

    ''' <summary>
    ''' 创建实例
    ''' </summary>
    ''' <param name="tel">号码</param>
    ''' <param name="pass">密码</param>
    ''' <remarks></remarks>
    Public Sub New(ByVal tel As String, ByVal pass As String)
        TelNo = tel
        TelPass = pass
        TelProtectedPass = pass
        web.Encoding = Text.Encoding.UTF8
    End Sub

    Public Sub New(ByVal tel As String, ByVal pass As String, ByVal protectedpass As String)
        TelNo = tel
        TelPass = pass
        TelProtectedPass = protectedpass
        web.Encoding = Text.Encoding.UTF8
    End Sub

    ''' <summary>
    ''' 获得验证码
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetVerifyCode()
        Dim retVal As String = web.DownloadString("http://www.c4006.com/user/servlet/verify.tslogin")
        Dim o As JsonReturn = GetJson(retVal)
        If o.success Then
            Return o.message
        End If
        Return retVal
    End Function


    ''' <summary>
    ''' 登录
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function Login() As String
        Dim vcode As String = GetVerifyCode()
        Dim url As String = String.Format("http://www.c4006.com/user/servlet/login.tslogin?userName={0}&passWord={1}&verifyCode={2}&verifyHidden={3}", TelNo, TelPass, vcode, vcode)
        Dim retVal As String = web.DownloadString(url)
        'Dim Cookie As String = web.ResponseHeaders(HttpResponseHeader.SetCookie)
        'if (cCookie.IndexOf(";") != -1) { cCookie = cCookie.Substring(0, cCookie.IndexOf(";")); }
        Dim o As JsonReturn = GetJson(retVal)
        If o.success Then
            'isLogin = True
            web.Cookies.Add(New System.Net.Cookie("telno", TelNo, "/", "www.c4006.com"))
            Return True
        Else
            Return retVal
        End If
    End Function

    ''' <summary>
    ''' 新增分机
    ''' </summary>
    ''' <param name="num">分机号</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function AddExt(ByVal name As String, ByVal num As String) As String
        If Not isLogin Then Login()
        If TelId = -1 Then TelId = GetTelId()

        Dim url As String = String.Format("http://www.c4006.com/customer/servlet/AddExtension.ts?ExtensionNumId={0}&flag=2&calltype=1&workdayid=-1", TelId)
        Dim data As String = String.Format("ExtendsionType=on&departName={0}&extendtionNum={1}&usenum=on&workdaysset=%E6%8E%A5%E5%90%AC%E6%89%80%E6%9C%89", name, num)
        web.Headers.Add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
        Dim retVal As String = web.UploadString(url, data)
        Return retVal
    End Function

    ''' <summary>
    ''' 修改分机信息
    ''' </summary>
    ''' <param name="id"></param>
    ''' <param name="name"></param>
    ''' <param name="num"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ModifyExt(ByVal id As String, ByVal name As String, ByVal num As String) As String
        If Not isLogin Then Login()
        Dim url As String = String.Format("http://www.c4006.com/customer/servlet/ModifyExtensionAndWorkDay.ts?ExtensionNumId={0}&flag=2&calltype=1&workdayid=undefined", id)
        Dim data As String = String.Format("departName={0}&extendtionNum={1}&keyNum=0&wordsRvoice_before=-1&busyLeaveMsgVoice=&usenum=on&workdaysset=%E6%8E%A5%E5%90%AC%E6%89%80%E6%9C%89", name, num)
        web.Headers.Add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
        Dim retVal As String = web.UploadString(url, data)
        Return retVal
    End Function


    ''' <summary>
    ''' 删除分机号
    ''' </summary>
    ''' <param name="numid">分机ID</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function DelExt(ByVal numid As String) As String
        If Not isLogin Then Login()
        If isprotect Then UnProtected()
        Dim url As String = String.Format("http://www.c4006.com/customer/servlet/DelExtension.ts?ExtensionNumId={0}&isforce=1", numid)

        Dim retVal As String = web.DownloadString(url)

        Return retVal

    End Function

    Public Function GetExtCallLog(ByVal numid As String, ByVal page As String) As String
        If Not IsLogin() Then Login()
        If isprotect Then UnProtected()

        Dim url As String = String.Format("http://www.c4006.com/customer/servlet/GetTongHuas.ts?nodesid={0}&start={1}&Limit=20", numid, page - 1)
        Dim retVal As String = web.DownloadString(url)
        Return retVal
    End Function

    ''' <summary>
    ''' 通用Get获取数据
    ''' </summary>
    ''' <param name="url">网址</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function doGet(ByVal url As String) As String
        If Not IsLogin() Then Login()
        If isprotect() Then UnProtected()
        If url.StartsWith("/") Then
            url = String.Concat("http://", Domain, url)
        End If
        Dim retval As String = web.DownloadString(url)
        Return retval
    End Function

    ''' <summary>
    ''' 通用POST提交数据
    ''' </summary>
    ''' <param name="url">网址</param>
    ''' <param name="data">数据</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function doPost(ByVal url As String, ByVal data As String) As String
        Dim retVal As String = String.Empty
        If Not IsLogin() Then retVal = Login()
        If isprotect() Then UnProtected()
        web.Headers.Add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")

        If url.StartsWith("/") Then
            url = String.Concat("http://", Domain, url)
        End If
        retVal = web.UploadString(url, data)
        Return retVal
    End Function



    ''' <summary>
    ''' 获取分机所有座席号码
    ''' </summary>
    ''' <param name="id">分机编号</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function BindPhone(ByVal id As String) As String
        Return BindPhone(id, Nothing)
    End Function

    ''' <summary>
    ''' 绑定座席号码
    ''' </summary>
    ''' <param name="id">分机编号</param>
    ''' <param name="phone">座席号码</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function BindPhone(ByVal id As String, ByVal phone As String) As String
        If Not IsLogin() Then Login()

        Dim url As String
        If String.IsNullOrEmpty(phone) Then
            url = String.Format("http://www.c4006.com/customer/servlet/GetExtensionNum.ts?ExtensionNumId={0}", id)
            Dim retVal As String = web.DownloadString(url)
            Return retVal
        Else
            url = String.Format("http://www.c4006.com/customer/servlet/AddExtensionNum.ts?ExtensionNumId={0}&bindPhone={1}&delayTime=15", id, phone)
            Dim retVal As String = web.DownloadString(url)
            Return retVal
        End If
    End Function

    ''' <summary>
    ''' 绑定座席号码
    ''' </summary>
    ''' <param name="id">座席编号</param>
    ''' <param name="phone">座席号码</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ModifyBindPhone(ByVal id As String, ByVal phone As String) As String

        Dim url As String = String.Format("http://www.c4006.com/customer/servlet/ModifyBindPhoneAndWordDay.ts?ExtensionNumId={0}&workdayid=-1", id)
        Dim data As String = String.Format("turnnum={0}&waitminute=15&workdaysset=%E6%8E%A5%E5%90%AC%E6%89%80%E6%9C%89", phone)
        Return doPost(url, data)

    End Function

    ''' <summary>
    ''' 取消号码绑定
    ''' </summary>
    ''' <param name="id">号码编号</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function DelBindPhone(ByVal id As String) As String
        If Not IsLogin() Then Login()
        If isprotect() Then UnProtected()
        Dim url As String = String.Format("http://www.c4006.com/customer/servlet/DelExtensionNum.ts?ExtensionNumId={0}", id)
        Dim retVal As String = web.DownloadString(url)
        Return retVal
    End Function

    ''' <summary>
    ''' 取消保护模式
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function UnProtected() As String
        Dim retVal As String = String.Empty
        If Not IsLogin() Then Login()
        Dim url As String = String.Format("http://www.c4006.com/customer/servlet/InPutSencodPwd.ts")
        web.Headers.Add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
        retVal = web.UploadString(url, String.Format("sencodpwd={0}", TelProtectedPass))
        web.Headers.Remove("Content-Type")
        Dim o As JsonReturn = GetJson(retVal)
        If o.success Then
            web.Cookies.Add(New System.Net.Cookie("unprotected", TelNo, "/", "www.c4006.com"))
            Return True
        Else
            Return o.message
        End If
        Return retVal
    End Function

    ''' <summary>
    ''' 获得指定的分机信息
    ''' </summary>
    ''' <param name="numid">分机ID</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetExt(ByVal numid As String) As String
        If Not IsLogin() Then Login()
        Dim url As String
        If String.IsNullOrEmpty(numid) Then
            url = String.Format("http://www.c4006.com/customer/servlet/GetExtensionTree.ts")
        Else
            url = String.Format("http://www.c4006.com/customer/servlet/GetExtension.ts?ExtensionNumId={0}", numid)
        End If
        Dim retVal As String = web.DownloadString(url)

        Return retVal

    End Function

    ''' <summary>
    ''' 获得分机信息
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetExt() As String
        Return GetExt(Nothing)
    End Function

    Public Function IsLogin() As Boolean
        Dim uri As New System.Uri("http://www.c4006.com")
        Dim c As System.Net.Cookie = Cookies.GetCookies(uri)("telno")
        If Not c Is Nothing AndAlso c.Value = TelNo Then
            Return True
        End If
        Return False
    End Function

    Public Function isprotect() As Boolean
        Dim uri As New System.Uri("http://www.c4006.com")
        Dim c As System.Net.Cookie = Cookies.GetCookies(uri)("unprotected")
        If Not c Is Nothing AndAlso c.Value = TelNo Then
            Return False
        End If
        Return True
    End Function


    ''' <summary>
    ''' 获得总机ID
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetTelId() As Integer
        If Not IsLogin() Then Login()
        Dim url As String = String.Format("http://www.c4006.com/customer/servlet/GetExtensionTree.ts")
        Try
            Dim retVal As String = web.DownloadString(url)
            Dim jsonArray As JavaScriptArray = CType(JavaScriptConvert.DeserializeObject(retVal), JavaScriptArray)
            Return jsonArray(0)("id")
        Catch ex As Exception
            Return -500
        End Try
        Return -1
    End Function

    ''' <summary>
    ''' 转换String To JSON
    ''' </summary>
    ''' <param name="s"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetJson(ByVal s As String) As JsonReturn
        Dim o As JsonReturn
        Try
            o = CType(JavaScriptConvert.DeserializeObject(s, GetType(JsonReturn)), JsonReturn)
        Catch ex As Exception
            o = New JsonReturn
            o.success = False
            o.message = ex.Message
        End Try
        Return o
    End Function

    Public Function UrlEncode(ByVal str As String) As String
        Dim sb As New StringBuilder()
        Dim byStr As Byte() = System.Text.Encoding.UTF8.GetBytes(str) '默认是System.Text.Encoding.Default.GetBytes(str)
        For i = 0 To byStr.LongLength - 1
            sb.Append("%" + Convert.ToString(byStr(i), 16))
        Next
        Return sb.ToString()
    End Function
End Class

Public Class JsonReturn
    Public success As Boolean = False
    Public data As Object
    Public message As String
    Public messagetwo As String = String.Empty
    Public ExtensionNumId As Integer = -1
End Class

Public Class JsonExt
    Public text As String
    Public id As String
    Public leaf As String
    Public cls As String
    Public children As JsonExt()
End Class





